package com.codechuan.hallo_internal.utils;

import android.util.Log;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.codechuan.hallo_internal.floatwindow.FloatWindowManager;
import com.codechuan.hallo_internal.common.Constant;
import com.codechuan.hallo_internal.entity.CityInfo;
import com.codechuan.hallo_internal.entity.FilterOrder;
import com.codechuan.hallo_internal.entity.SuccessOrder;
import com.codechuan.hallo_internal.floatwindow.log.LogManager;
import com.codechuan.hallo_internal.thread.SynContainer;
import com.codechuan.hallo_internal.ui.home.HomeFragment;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.NumberFormat;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @Deprecated 哈喽项目的接口工具类
 */
public class HalloProjectHttpUtil {

    /**
     * @Deprecated 获取小程序验证码
     */
    public static String getWeChatMiniProgramCode(String phone) {
        OkHttpClient client = new OkHttpClient();
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("action", "user.account.sendCodeV2");
        hashMap.put("systemCode", "Aj4");
        hashMap.put("env", "pro");
        hashMap.put("mobile", phone);
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JSONObject.toJSONString(hashMap));
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url("https://api.hellobike.com/api?user.account.sendCodeV2")
                .post(body)
                .addHeader("Host", "api.hellobike.com")
                .addHeader("Connection", "keep-alive")
                .addHeader("content-type", "application/json")
                .addHeader("Accept-Encoding", "gzip,compress,br,deflate")
                .addHeader("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.49(0x1800312d) NetType/WIFI Language/zh_CN")
                .build();
        // 发送请求并获取响应
        Response response = null;
        try {
            response = client.newCall(request).execute();
            assert response.body() != null;
            JSONObject jsonObject = JSONObject.parseObject(response.body().string());
            assert jsonObject != null;
            String status = jsonObject.getString("code");
            if (status.equals("0")) {
                return "发送成功";
            } else {
                return jsonObject.getString("msg");
            }

        } catch (IOException e) {
            return "发送异常";
        }
    }


    /**
     * @Deprecated 获取小程序Token
     */
    public static JSONObject getWeChatMiniProgramToken(String phone, String code) {
        OkHttpClient client = new OkHttpClient();
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("action", "user.account.weixinMobileLogin");
        hashMap.put("platform", "1");
        hashMap.put("env", "pro");
        hashMap.put("systemCode", "Aj4");
        hashMap.put("channel", "26");
        hashMap.put("mobile", phone);
        hashMap.put("code", code);
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JSONObject.toJSONString(hashMap));
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url("https://api.hellobike.com/api?user.account.weixinMobileLogin")
                .post(body)
                .addHeader("Host", "api.hellobike.com")
                .addHeader("Connection", "keep-alive")
                .addHeader("content-type", "application/json")
                .addHeader("Accept-Encoding", "gzip,compress,br,deflate")
                .addHeader("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.49(0x1800312d) NetType/WIFI Language/zh_CN")
                .build();
        // 发送请求并获取响应
        Response response = null;
        try {
            response = client.newCall(request).execute();
            assert response.body() != null;
            JSONObject jsonObject = JSONObject.parseObject(response.body().string());
            assert jsonObject != null;
            String status = jsonObject.getString("code");
            if (status.equals("0")) {
                JSONObject data = JSONObject.parseObject(jsonObject.getString("data"));
                String ticket = data.getString("ticket");
                String firstLogin = data.getString("firstLogin");
                String userNewId = data.getString("userNewId");
                String newUser = data.getString("newUser");
                String mobile = data.getString("mobile");
                String guid = data.getString("guid");
                String token = data.getString("token");
                System.out.println("ticket = " + ticket);
                System.out.println("firstLogin = " + firstLogin);
                System.out.println("userNewId = " + userNewId);
                System.out.println("newUser = " + newUser);
                System.out.println("mobile = " + mobile);
                System.out.println("guid = " + guid);
                System.out.println("token = " + token);
                System.out.println("success");
                return data;
            } else {
                return null;
            }

        } catch (IOException e) {
            return null;
        }
    }

    /**
     * @param cityInfo 城市信息
     * @Deprecated 获取APP大厅订单接口
     */
    public static void getWeChatAppProgramOrderList(CityInfo cityInfo, SynContainer synContainer, String name) {
        if (Constant.isTxm)
        {
            return;
        }
        OkHttpClient client = new OkHttpClient();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("action", "hitch.driver.journeyList");
        hashMap.put("clientId", ""); // 城市id
        hashMap.put("systemCode", "62"); // 系统代码

        hashMap.put("token", Constant.token); // 用户令牌
        hashMap.put("ticket", Constant.ticket); // 用户标识 ticket
        hashMap.put("version", "6.76.5");

        hashMap.put("adCode", cityInfo.getAdCode()); // 城市邮编
        hashMap.put("cityCode", cityInfo.getCityId()); // 城市区号
        hashMap.put("lat", cityInfo.getLat()); //坐标 纬度
        hashMap.put("lon", cityInfo.getLng()); //坐标 经度
        hashMap.put("apkSignHash", "zkrFhoDpIPlkKlif+uTNtL1EYctTSHr7vJ/GE641gE4=\n");

        hashMap.put("bearHighwayFeeType", 0);
        hashMap.put("carpoolDeliverJointThreeOrders", false);
        hashMap.put("clickLat", "");
        hashMap.put("clickLon", "");
        hashMap.put("currentOrderGuids", new String[0]);
        hashMap.put("driverHomePageV2", false);
        hashMap.put("journeyType", 1);
        Integer[] journeyTypeList = {1};
        hashMap.put("journeyTypeList", journeyTypeList);

        hashMap.put("pageIndex", 1);//页面索引
        hashMap.put("pageSessionId", "");
        hashMap.put("pageSize", 10);
        hashMap.put("receivedPoolAgain", false);

        hashMap.put("requestSource", 0);
        hashMap.put("requestType", Constant.requestType);//获取类型 3=城际大厅 2=市内

        HashMap<String, Object> requestType3Param = new HashMap<>();
        requestType3Param.put("adCode", cityInfo.getAdCode());
        requestType3Param.put("cityCode", cityInfo.getCityId());

        requestType3Param.put("endAdCode", "");
        requestType3Param.put("endAdCodeList", new String[0]);

        requestType3Param.put("endCityCode", "");
        requestType3Param.put("endCityCodeList", "");
        if (!Constant.cityCodeList.isEmpty() && Constant.ZD_CS_CHECK) {
            requestType3Param.put("endCityCodeList", Constant.cityCodeList);
        }
        if (Constant.ZD_CS_CHECK && Constant.cityCodeList.isEmpty()) {
            return;
        }
        // 设置过滤器
        requestType3Param.put("filters", new String[0]);
        if (Constant.ZJ_DX) {
            ArrayList<FilterOrder> filterOrders = new ArrayList<>();
            FilterOrder filterOrder = new FilterOrder("0", "", "", "orderType");
            filterOrders.add(filterOrder);
            requestType3Param.put("filters", filterOrders);
        }
        if (Constant.YD_GS) {
            ArrayList<FilterOrder> filterOrders = new ArrayList<>();
            FilterOrder filterOrder = new FilterOrder("1", "", "", "bearHighWayFeeType");
            filterOrders.add(filterOrder);
            requestType3Param.put("filters", filterOrders);
        }
        if (Constant.ZJ_DX && Constant.YD_GS) {
            ArrayList<FilterOrder> filterOrders = new ArrayList<>();
            FilterOrder order = new FilterOrder("0", "", "", "orderType");
            FilterOrder gs = new FilterOrder("1", "", "", "bearHighWayFeeType");
            filterOrders.add(order);
            filterOrders.add(gs);
            requestType3Param.put("filters", filterOrders);
        }

        requestType3Param.put("lat", cityInfo.getLat());
        requestType3Param.put("lon", cityInfo.getLng());
        hashMap.put(Constant.requestTypeParam, requestType3Param); // 城际大厅 设置参数json

        hashMap.put("skipSourceType", 0);
        hashMap.put("sortMethod", Constant.SORT);//订单排序方式 1=智能 2=最早 3=最近 4=最高
        hashMap.put("timeRange", 0);
        hashMap.put("sid", "");

        HashMap<String, Object> riskControlData = new HashMap<>();
        riskControlData.put("deviceLat", Double.parseDouble(Constant.cityInfo.getLat()));
        riskControlData.put("deviceLon", Double.parseDouble(Constant.cityInfo.getLng()));
        riskControlData.put("systemCode", "62");
        riskControlData.put("network", "Wifi");
        riskControlData.put("mobileNoInfo", "");
        riskControlData.put("ssidName", "");
        riskControlData.put("capability", "");
        riskControlData.put("roam", "");
        riskControlData.put("batteryLevel", "");
        riskControlData.put("isMock", 1);
        hashMap.put("riskControlData", riskControlData);
        MediaType mediaType = MediaType.parse("application/xml; charset=utf-8");
        String encrypt = null;
        try {

            encrypt = Demo.encrypt(JSONObject.toJSONString(hashMap));
        } catch (Exception e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(mediaType, encrypt);
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url("https://taxiapi.hellobike.com/api")
                .post(body)
                .addHeader("Host", "taxiapi.hellobike.com")
                .addHeader("Connection", "keep-alive")
                .addHeader("content-type", "application/json; charset=UTF-8")
                .addHeader("user-agent", "Mozilla/5.0 (Linux; Android 13; 23049RAD8C Build/TKQ1.221114.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/127.0.6533.103 Mobile Safari/537.36")
                .addHeader("inner_action", "hitch.driver.journeyList")
                .addHeader("systemcode", "62")
                .addHeader("chaos", "true")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                response = client.newCall(request).execute();
                assert response.body() != null;
                try {
                    String decrypt = Demo.decrypt(response.body().string());
                    Constant.executorService.execute(new Runnable() {
                        @Override
                        public void run() {
                            JSONObject jsonObjectOne = JSONObject.parseObject(decrypt);
                            String status = jsonObjectOne.getString("code");
                            if (status.equals("0")) {
                                // todo 开始匹配条件
                                JSONObject jsonObject = JSONObject.parseObject(jsonObjectOne.toString());
                                JSONObject data = jsonObject.getJSONObject("data");
                                if (data == null) {
                                    return;
                                }
                                JSONArray jsonArray = data.getJSONArray("list");
                                if (jsonArray.isEmpty())
                                    LogManager.get().addLog("获取到0个订单");
                                for (Object o : jsonArray) {
                                    JSONObject listData = JSONObject.parseObject(o.toString());
                                    // 获取起点位置名称
                                    JSONObject startAddress = listData.getJSONObject("startAddr");
                                    JSONObject endAddress = listData.getJSONObject("endAddr");

                                    String endDistanceString = listData.getString("distance");
                                    double endDistanceDouble = Double.parseDouble(endDistanceString);
                                    endDistanceDouble = endDistanceDouble / 1000;

                                    // 金额判断(除100)
                                    Integer price = listData.getInteger("price");
                                    price = price / 100;
                                    LogManager.get().addLog("起点:" + startAddress.getString("longAddr") + "\t至" + endAddress.getString("longAddr") + "\t全程:" + endDistanceDouble + "KM" + "\t金额:" + price + "元");
                                    if (price <= Constant.MIN_MONEY || price >= Constant.MAX_MONEY) {
                                        continue;
                                    }

                                    // 开始时间结束时间判断
                                    Long startPlanStartTime = listData.getLong("startPlanStartTime");
                                    Long endPlanStartTime = listData.getLong("endPlanStartTime");

                                    Date startPlanStartTimeDate = DateUtil.passDate(DateUtil.LongTimeParseStingTime(startPlanStartTime));
                                    Date endPlanStartTimeDate = DateUtil.passDate(DateUtil.LongTimeParseStingTime(endPlanStartTime));
                                    // 订单开始时间小于自己设置的时间就跳出 after左边时间大于右边时间返回真
                                    if (!startPlanStartTimeDate.after(Constant.START_TIME)) {
                                        continue;
                                    }
                                    // 自己设置的结束时间小于订单结束时间就跳出
                                    if (endPlanStartTimeDate.after(Constant.END_TIME)) {
                                        continue;
                                    }

                                    // 订单类型
                                    String carPoolText = listData.getString("carPoolText");

                                    // 起点小于校验值判断
                                    String startDistanceString = listData.getString("startDistance");
                                    double startDistanceDouble = Double.parseDouble(startDistanceString);
                                    startDistanceDouble = startDistanceDouble / 1000;
                                    if (Double.parseDouble(String.valueOf(Constant.DT_START_DES)) < startDistanceDouble) {
                                        continue;
                                    }

                                    // 终点小于校验值判断
                                    if (endDistanceDouble > Double.parseDouble(String.valueOf(Constant.DT_END_DES))) {
                                        System.out.println("终点距离跳出" + String.valueOf(endDistanceDouble > Double.parseDouble(String.valueOf(Constant.DT_END_DES))));
                                        continue;
                                    }


                                    // 获取乘坐人数
                                    Integer passengerCount = listData.getInteger("passengerCount");
                                    // 如果勾选了拼车开始进行拼车单校验
                                    if (Constant.PC_PERSON_CHECKBOX && "拼座".equals(carPoolText)) {
                                        if (passengerCount < Constant.PC_MIN_NUMBER || passengerCount > Constant.PC_MAX_NUMBER) {
                                            continue;
                                        }
                                    }
                                    // 如果没有勾选但是单子是拼车直接跳出
                                    if (!Constant.PC_PERSON_CHECKBOX && "拼座".equals(carPoolText)) {
                                        continue;
                                    }

                                    // 如果勾选了独享开始进行独享单校验
                                    if (Constant.DX_PERSON_CHECKBOX && "独享".equals(carPoolText)) {
                                        if (passengerCount < Constant.DX_MIN_NUMBER || passengerCount > Constant.DX_MAX_NUMBER) {
                                            continue;
                                        }
                                    }
                                    // 如果没有勾选但是单子是独享直接跳出
                                    if (!Constant.DX_PERSON_CHECKBOX && "独享".equals(carPoolText)) {
                                        continue;
                                    }

                                    // 如果勾选了舒适开始进行舒适单校验
                                    if (Constant.SS_PERSON_CHECKBOX && !"独享".equals(carPoolText) && !"拼座".equals(carPoolText)) {
                                        if (passengerCount < Constant.SS_MIN_NUMBER || passengerCount > Constant.SS_MAX_NUMBER) {
                                            continue;
                                        }
                                    }
                                    // 如果没有勾选但是单子是适合拼直接跳出
                                    if (!Constant.SS_PERSON_CHECKBOX && !"独享".equals(carPoolText) && !"拼座".equals(carPoolText)) {
                                        continue;
                                    }

                                    // 开始计算单价金额
                                    Double dj_money = price / endDistanceDouble;
                                    NumberFormat nf = NumberFormat.getNumberInstance();
                                    nf.setMaximumFractionDigits(2); // 设置最大小数位数为2
                                    String formattedValue = nf.format(dj_money);
                                    // 判断单价设置
                                    if (Constant.PC_TH_CHECK) {
                                        if (Double.parseDouble(formattedValue) < 1.4) {
                                            continue;
                                        }
                                    }
                                    // todo 结束匹配条件

                                    String shortAddress = startAddress.getString("shortAddr");
                                    // 获取订单id
                                    String journeyId = listData.getString("journeyId");
                                    // 重复订单处理
                                    if (Constant.stringBuilder.toString().contains(journeyId))
                                        continue;
                                    Constant.stringBuilder.append(journeyId).append(",");
                                    // 判断排除地区
                                    if (Constant.PC_CS_TEXT != null && Constant.PC_CS_CHECK) {
                                        if (Constant.PC_CS_TEXT.contains(startAddress.getString("cityName"))) {
                                            continue;
                                        }
                                    }
                                    // todo 匹配符合的生成订单类对象
                                    SuccessOrder successOrder = new SuccessOrder();
                                    successOrder.setShortAddr(shortAddress);
                                    successOrder.setPassengerGuid(listData.getString("passengerGuid"));
                                    successOrder.setPaxJourneyGuid(journeyId);
                                    successOrder.setCityCode(cityInfo.getCityId());
                                    successOrder.setAdCode(cityInfo.getAdCode());
                                    successOrder.setLon(startAddress.getString("lon"));
                                    successOrder.setLat(startAddress.getString("lat"));
                                    successOrder.setSjLon(cityInfo.getLng());
                                    successOrder.setSjLat(cityInfo.getLat());
                                    successOrder.setPlanArriveTime(listData.getLong("planArriveTime"));
                                    successOrder.setPrice(String.valueOf(price));
                                    successOrder.setPersonNumber(String.valueOf(passengerCount));
                                    successOrder.setOrderDes(String.valueOf(endDistanceDouble));
                                    successOrder.setCarPoolText(carPoolText);
                                    successOrder.setStartAddress(startAddress.getString("longAddr"));
                                    successOrder.setEndAddress(endAddress.getString("longAddr"));
                                    successOrder.setPassengerName(listData.getString("passengerName"));
                                    successOrder.setAdName(startAddress.getString("adName"));
                                    successOrder.setBizArea(startAddress.getString("bizArea"));
                                    successOrder.setCityName(startAddress.getString("cityName"));
                                    successOrder.setStartDes(String.valueOf(startDistanceDouble));
                                    synContainer.setSuccessOrder(successOrder);
                                }
                            } else {
                                if (status.equals("99")) {
                                    Constant.isTxm = true;
                                    Constant.handler.post(() -> {
                                        DialogUtil.showDialog(ContextUtil.context, "开始处理图形验证中~");
                                    });
                                    JSONObject jsonObject = JSONObject.parseObject(jsonObjectOne.toString());
                                    String data = jsonObject.getString("data");

                                    String proxy = configureTasks();
                                    Constant.handler.post(() -> {
                                        DialogUtil.showDialog(ContextUtil.context, "等待图形码结果~");
                                    });
                                    String sid = UUID.randomUUID().toString().replaceAll("-", "");
                                    HashMap<String, String> hashMap1 = MyProjectHttpUtil.initSlider(data, Constant.token, Constant.ticket, sid);
                                    if (hashMap1 == null)
                                    {
                                        // 获取图形码服务器和处理图形码服务器
                                        JSONObject fuck = MyProjectHttpUtil.fuck();
                                        String encrypt2 = "";
                                        try {
                                            encrypt2 = Demo.encrypt(JSONObject.toJSONString(hashMap));
                                        } catch (Exception e) {
                                            Constant.handler.post(() -> DialogUtil.showDialog(ContextUtil.context, e.getMessage()));
                                        }
                                        MyProjectHttpUtil.demo(encrypt2,Constant.token,Constant.ticket,fuck);
                                        return;
                                    }
                                    // 获取图形码服务器和处理图形码服务器
                                    JSONObject fuck = MyProjectHttpUtil.fuck();

                                    // 第二步过验证码
                                    MyProjectHttpUtil.txm(Constant.ticket, Constant.token, data, proxy, fuck,hashMap1.get("challenge"),hashMap1.get("captchaId"),sid);
                                }
                                if (status.equals("103") && Constant.errorNumber > 3) {
                                    Constant.isStart = false;
                                    Constant.handler.post(() -> {
                                        DialogUtil.showDialog(ContextUtil.context, "主号token过期~");
                                    });
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            // 修改用户token状态
                                            MyProjectHttpUtil.updateAccountTokenStatus();
                                        }
                                    }).start();
                                }
                                Constant.errorNumber++;
                            }
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * @Deprecated 执行App接单
     */
    public static void submitWeChatAppOrder(SuccessOrder successOrder) {
        OkHttpClient client = new OkHttpClient();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("action", "hitch.driver.receiveOrder");
        hashMap.put("clientId", "");
        hashMap.put("systemCode", "62");

        hashMap.put("ticket", Constant.ticket);
        hashMap.put("token", Constant.token);

        hashMap.put("version", "6.76.5");

        hashMap.put("adCode", Constant.cityInfo.getAdCode());
        hashMap.put("cityCode", Constant.cityInfo.getCityId());
        hashMap.put("lat", successOrder.getLat());
        hashMap.put("lon", successOrder.getLon());

        hashMap.put("apkSignHash", "zkrFhoDpIPlkKlif+uTNtL1EYctTSHr7vJ/GE641gE4=\n");
        hashMap.put("bounty", 0);
        hashMap.put("bountyGuid", "");

        HashMap<String, Object> driverStartAddress = new HashMap<>();
        driverStartAddress.put("adCode", Constant.cityInfo.getAdCode());
        driverStartAddress.put("adName", successOrder.getAdName());
        driverStartAddress.put("addrType", 0);
        driverStartAddress.put("bizArea", successOrder.getBizArea());
        driverStartAddress.put("cityCode", successOrder.getCityCode());
        driverStartAddress.put("cityName", successOrder.getCityName());
        driverStartAddress.put("lat", successOrder.getLat());
        driverStartAddress.put("lon", successOrder.getLon());
        driverStartAddress.put("longAddr", successOrder.getStartAddress());
        driverStartAddress.put("poiId", "");
        driverStartAddress.put("poiInfo", "");
        driverStartAddress.put("recommend", false);
        driverStartAddress.put("shortAddr", successOrder.getShortAddr());
        driverStartAddress.put("source", 0);
        driverStartAddress.put("streetInfo", "");
        hashMap.put("driverStartAddress", driverStartAddress);

        hashMap.put("hitchPercent", "0.99");
        hashMap.put("invalidOrderGreyResult", false);
        hashMap.put("paxJourneyGuid", successOrder.getPaxJourneyGuid());
        hashMap.put("passengerGuid", successOrder.getPassengerGuid());
        hashMap.put("planArriveTime", "");
        hashMap.put("receiveOrderDriverSourceType", 0);
        hashMap.put("receiveSourceType", 7);
        hashMap.put("relativeFriend", 0);
        hashMap.put("sourceType", 1);
        hashMap.put("totalBounty", 0);
        hashMap.put("useDefaultVehicle", false);
        hashMap.put("sid", "");

        HashMap<String, Object> riskControlData = new HashMap<>();
        riskControlData.put("deviceLat", successOrder.getLat());
        riskControlData.put("deviceLon", successOrder.getLon());
        riskControlData.put("systemCode", "62");
        riskControlData.put("network", "wifi");
        riskControlData.put("mobileNoInfo", "");
        riskControlData.put("ssidName", "");
        riskControlData.put("capability", "");
        riskControlData.put("roam", "");
        riskControlData.put("batteryLevel", "");

        hashMap.put("riskControlData", riskControlData);
        MediaType mediaType = MediaType.parse("application/json");
        String encrypt = null;
        try {
            encrypt = EncryptionUtil.encrypt(JSONObject.toJSONString(hashMap));
        } catch (Exception e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(mediaType, encrypt);
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url("https://taxiapi.hellobike.com/api")
                .post(body)
                .addHeader("Host", "taxiapi.hellobike.com")
                .addHeader("content-type", "application/json; charset=UTF-8")
                .addHeader("user-agent", "Mozilla/5.0 (Linux; Android 13; 23049RAD8C Build/TKQ1.221114.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/127.0.6533.103 Mobile Safari/537.36")
                .addHeader("inner_action", "hitch.driver.journeyList")
                .addHeader("systemcode", "62")
                .addHeader("chaos", "true")
                .build();
        // 发送请求并获取响应
        Response response = null;

        try {
            response = client.newCall(request).execute();
            String decrypt = Demo.decrypt(response.body().string());
            JSONObject jsonObjectOne = JSONObject.parseObject(decrypt);
            String status = jsonObjectOne.getString("code");
            // 失败消息
            String msg = null;
            JSONObject data = jsonObjectOne.getJSONObject("data");
            if (status.equals("100000")) {
                JSONObject commonAlert = data.getJSONObject("commonAlert");
                // 拼接信息
                String title = commonAlert.getJSONObject("title").getString("text");
                String content = commonAlert.getJSONObject("content").getString("text");
                msg = title + ":" + content;
            }
            if (data != null) {
                if (status.equals("0") && data.getBoolean("joinPkSuccess")) {
                    msg = "成功加入PK.";
                } else {
                    JSONObject commonAlert = data.getJSONObject("commonAlert");
                    // 拼接信息
                    String title = commonAlert.getJSONObject("title").getString("text");
                    String content = commonAlert.getJSONObject("content").getString("text");
                    msg = title + ":" + content;
                }
            }
            if (status.equals("880")) {
                msg = "此订单已加入PK";
            }
            if (status.equals("865")) {
                msg = "成功加入PK";
            }
            if (status.equals("10000")) {
                msg = "APP未刷脸认证";
            }
            if (status.equals("103")) {
                msg = "主号登录过期";
                Constant.isStart = false;
                LogManager.get().startLog();
            }

            LogManager.get().addLog(msg);
            HomeFragment.updateStartCodeText(msg);
            successOrder.setOrderType("APP");
            // 插入数据库
            System.out.println("PK结果:" + msg);
            LogManager.get().addLog(msg);
            if (!Constant.mediaPlayer.isPlaying()) {
                Constant.mediaPlayer.start();
            }
            successOrder.setMsg(msg);
            successOrder.setOrderType("APP");
            successOrder.setAccount(Constant.account);
            String finalMsg = msg;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    MyProjectHttpUtil.addUserOrder(successOrder);
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param cityInfo 城市信息
     * @Deprecated 获取小程序大厅订单接口
     */
    public static void getWeChatMiniProgramOrderListTwo(CityInfo cityInfo, SynContainer synContainer) {

        OkHttpClient client = new OkHttpClient();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("action", "hitch.driver.journeyList");
        hashMap.put("clientId", ""); // 城市id
        hashMap.put("systemCode", "62"); // 系统代码
        hashMap.put("token", Constant.token); // 用户令牌
        hashMap.put("ticket", Constant.ticket); // 用户标识 ticket

        hashMap.put("version", "6.76.5");

        hashMap.put("adCode", cityInfo.getAdCode()); // 城市邮编
        hashMap.put("cityCode", cityInfo.getCityId()); // 城市区号

        hashMap.put("lat", cityInfo.getLat()); //坐标 纬度
        hashMap.put("lon", cityInfo.getLng()); //坐标 经度
        hashMap.put("apkSignHash", "zkrFhoDpIPlkKlif+uTNtL1EYctTSHr7vJ/GE641gE4=\n");

        hashMap.put("bearHighwayFeeType", 0);
        hashMap.put("carpoolDeliverJointThreeOrders", false);
        hashMap.put("clickLat", "");
        hashMap.put("clickLon", "");
        hashMap.put("currentOrderGuids", new String[0]);
        hashMap.put("driverHomePageV2", false);
        hashMap.put("journeyType", 1);
        hashMap.put("journeyTypeList", new String[0]);

        hashMap.put("pageIndex", 1);//页面索引
        hashMap.put("pageSessionId", "");
        hashMap.put("pageSize", 10);
        hashMap.put("receivedPoolAgain", false);

        hashMap.put("requestSource", 0);
        hashMap.put("requestType", Constant.requestType);// 获取类型 3=城际大厅 2=市内

        HashMap<String, Object> requestType3Param = new HashMap<>();
        requestType3Param.put("adCode", cityInfo.getAdCode());
        requestType3Param.put("cityCode", cityInfo.getCityId());
        requestType3Param.put("endAdCode", "");
        requestType3Param.put("endAdCodeList", new String[0]);
        requestType3Param.put("endCityCode", "");
        requestType3Param.put("endCityCodeList", "");
        if (!Constant.cityCodeList.isEmpty() && Constant.ZD_CS_CHECK) {
            requestType3Param.put("endCityCodeList", Constant.cityCodeList);
        }
        if (Constant.ZD_CS_CHECK && Constant.cityCodeList.isEmpty()) {
            return;
        }
        // 设置过滤器
        requestType3Param.put("filters", new String[0]);
        if (Constant.ZJ_DX) {
            ArrayList<FilterOrder> filterOrders = new ArrayList<>();
            FilterOrder filterOrder = new FilterOrder("0", "", "", "orderType");
            filterOrders.add(filterOrder);
            requestType3Param.put("filters", filterOrders);
        }
        if (Constant.YD_GS) {
            ArrayList<FilterOrder> filterOrders = new ArrayList<>();
            FilterOrder filterOrder = new FilterOrder("1", "", "", "bearHighWayFeeType");
            filterOrders.add(filterOrder);
            requestType3Param.put("filters", filterOrders);
        }
        if (Constant.ZJ_DX && Constant.YD_GS) {
            ArrayList<FilterOrder> filterOrders = new ArrayList<>();
            FilterOrder order = new FilterOrder("0", "", "", "orderType");
            FilterOrder gs = new FilterOrder("1", "", "", "bearHighWayFeeType");
            filterOrders.add(order);
            filterOrders.add(gs);
            requestType3Param.put("filters", filterOrders);
        }
        requestType3Param.put("lat", cityInfo.getLat());
        requestType3Param.put("lon", cityInfo.getLng());
        hashMap.put(Constant.requestTypeParam, requestType3Param); // 城际大厅 设置参数json
        hashMap.put("skipSourceType", 0);
        hashMap.put("sortMethod", Constant.SORT);//订单排序方式 1=智能 2=最早 3=最近 4=最高
        hashMap.put("timeRange", 0);
        hashMap.put("sid", "");
        Random random = new Random();
        int randomNumber = random.nextInt(100) + 1;
        HashMap<String, Object> riskControlData = new HashMap<>();
        riskControlData.put("deviceLat", cityInfo.getLat());
        riskControlData.put("deviceLon", cityInfo.getLng());
        riskControlData.put("systemCode", "62");
        riskControlData.put("network", "wifi");
        riskControlData.put("mobileNoInfo", "");
        riskControlData.put("ssidName", "");
        riskControlData.put("capability", "WPA_PSK");
        riskControlData.put("roam", "");
        riskControlData.put("batteryLevel", String.valueOf(randomNumber));
        riskControlData.put("isMock", 1);
        hashMap.put("riskControlData", riskControlData); //设备相关信息json
        MediaType mediaType = MediaType.parse("application/json");
        String jsonString = JSONObject.toJSONString(hashMap);

        RequestBody body = RequestBody.create(mediaType, jsonString);
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url("https://taxiapi.hellobike.com/api?hitch.driver.journeyListV2")
                .post(body)
                .build();
        // 发送请求并获取响应
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                response = client.newCall(request).execute();
                assert response.body() != null;
                JSONObject jsonObjectOne = JSONObject.parseObject(response.body().string());
                Constant.executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        assert jsonObjectOne != null;
                        String status = jsonObjectOne.getString("code");
                        if (status.equals("0")) {
                            // todo 开始匹配条件
                            JSONObject jsonObject = JSONObject.parseObject(jsonObjectOne.toString());
                            JSONObject data = jsonObject.getJSONObject("data");
                            if (data == null) {
                                return;
                            }
                            JSONArray jsonArray = data.getJSONArray("list");
                            for (Object o : jsonArray) {
                                JSONObject listData = JSONObject.parseObject(o.toString());
                                // 获取起点位置名称
                                JSONObject startAddress = listData.getJSONObject("startAddr");
                                JSONObject endAddress = listData.getJSONObject("endAddr");

                                String endDistanceString = listData.getString("startDistance");
                                double endDistanceDouble = Double.parseDouble(endDistanceString);
                                endDistanceDouble = endDistanceDouble / 1000;

                                // 金额判断(除100)
                                Integer price = listData.getInteger("price");
                                price = price / 100;
                                LogManager.get().addLog("起点:" + startAddress.getString("longAddr") + "\t至" + endAddress.getString("longAddr") + "\t全程:" + endDistanceDouble + "KM" + "\t金额:" + price + "元");
                                if (price <= Constant.MIN_MONEY || price >= Constant.MAX_MONEY) {
                                    continue;
                                }

                                // 开始时间结束时间判断
                                Long startPlanStartTime = listData.getLong("startPlanStartTime");
                                Long endPlanStartTime = listData.getLong("endPlanStartTime");
                                Date startPlanStartTimeDate = DateUtil.passDate(DateUtil.LongTimeParseStingTime(startPlanStartTime));
                                Date endPlanStartTimeDate = DateUtil.passDate(DateUtil.LongTimeParseStingTime(endPlanStartTime));
                                // 订单开始时间小于自己设置的时间就跳出  after左边时间大于右边时间返回真
                                if (!startPlanStartTimeDate.after(Constant.START_TIME)) {
                                    continue;
                                }
                                // 自己设置的结束时间小于订单结束时间就跳出
                                if (endPlanStartTimeDate.after(Constant.END_TIME)) {
                                    continue;
                                }


                                // 是否只接独享单判断
                                String carPoolText = listData.getString("carPoolText");

                                // 起点小于校验值判断
                                String startDistanceString = listData.getString("startDistance");
                                double startDistanceDouble = Double.parseDouble(startDistanceString);
                                startDistanceDouble = startDistanceDouble / 1000;
                                if (Double.parseDouble(String.valueOf(Constant.DT_START_DES)) < startDistanceDouble) {
                                    continue;
                                }

                                // 终点小于校验值判断
                                if (endDistanceDouble > Double.parseDouble(String.valueOf(Constant.DT_END_DES))) {
                                    continue;
                                }


                                // 获取乘坐人数
                                Integer passengerCount = listData.getInteger("passengerCount");
                                // 如果勾选了拼车开始进行拼车单校验
                                if (Constant.PC_PERSON_CHECKBOX && "拼座".equals(carPoolText)) {
                                    if (passengerCount < Constant.PC_MIN_NUMBER || passengerCount > Constant.PC_MAX_NUMBER) {
                                        continue;
                                    }
                                }
                                // 如果没有勾选但是单子是拼车直接跳出
                                if (!Constant.PC_PERSON_CHECKBOX && "拼座".equals(carPoolText)) {
                                    continue;
                                }

                                // 如果勾选了独享开始进行独享单校验
                                if (Constant.DX_PERSON_CHECKBOX && "独享".equals(carPoolText)) {
                                    if (passengerCount < Constant.DX_MIN_NUMBER || passengerCount > Constant.DX_MAX_NUMBER) {
                                        continue;
                                    }
                                }
                                // 如果没有勾选但是单子是独享直接跳出
                                if (!Constant.DX_PERSON_CHECKBOX && "独享".equals(carPoolText)) {
                                    continue;
                                }

                                // 如果勾选了舒适开始进行舒适单校验
                                if (Constant.SS_PERSON_CHECKBOX && "适合拼".equals(carPoolText)) {
                                    if (passengerCount < Constant.SS_MIN_NUMBER || passengerCount > Constant.SS_MAX_NUMBER) {
                                        continue;
                                    }
                                }
                                // 如果没有勾选但是单子是适合拼直接跳出
                                if (!Constant.SS_PERSON_CHECKBOX && "适合拼".equals(carPoolText)) {
                                    continue;
                                }

                                // 判断排除地区
                                if (Constant.PC_CS_TEXT != null && Constant.PC_CS_CHECK) {
                                    if (Constant.PC_CS_TEXT.contains(startAddress.getString("cityName"))) {
                                        continue;
                                    }
                                }
                                // 判断单价设置
                                // 开始计算单价金额
                                Double dj_money = price / endDistanceDouble;
                                NumberFormat nf = NumberFormat.getNumberInstance();
                                nf.setMaximumFractionDigits(2); // 设置最大小数位数为2
                                String formattedValue = nf.format(dj_money);
                                if (Constant.PC_TH_CHECK) {
                                    if (Double.parseDouble(formattedValue) < 1.5) {
                                        continue;
                                    }
                                }
                                String shortAddress = startAddress.getString("shortAddr");
                                // 获取订单id
                                String journeyId = listData.getString("journeyId");
                                //  匹配符合的生成订单类对象
                                SuccessOrder successOrder = new SuccessOrder();
                                successOrder.setShortAddr(shortAddress);
                                successOrder.setPaxJourneyGuid(journeyId);
                                successOrder.setCityCode(cityInfo.getCityId());
                                successOrder.setAdCode(cityInfo.getAdCode());
                                successOrder.setLon(startAddress.getString("lon"));
                                successOrder.setLat(startAddress.getString("lat"));
                                successOrder.setSjLon(cityInfo.getLng());
                                successOrder.setDriverJourneyGuid(Constant.SCHEDULE_ID);
                                successOrder.setSjLat(cityInfo.getLat());
                                successOrder.setPlanArriveTime(listData.getLong("planArriveTime"));
                                successOrder.setPrice(String.valueOf(price));
                                successOrder.setPersonNumber(String.valueOf(passengerCount));
                                successOrder.setOrderDes(String.valueOf(endDistanceDouble));
                                successOrder.setCarPoolText(carPoolText);
                                successOrder.setStartAddress(startAddress.getString("longAddr"));
                                successOrder.setEndAddress(endAddress.getString("longAddr"));
                                successOrder.setPassengerName(listData.getString("passengerName"));
                                successOrder.setStartDes(String.valueOf(startDistanceDouble));
                                synContainer.setSuccessOrder(successOrder);

                            }
                        } else {
                            if (status.equals("103") && Constant.errorNumber > 3) {
                                Constant.isStart = false;
                                Constant.handler.post(() -> {
                                    DialogUtil.showDialog(ContextUtil.context, "主号token过期~");
                                });
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        // 修改用户token状态
                                        MyProjectHttpUtil.updateAccountTokenStatus();
                                    }
                                }).start();
                            }
                            Constant.errorNumber++;
                        }
                    }
                });
            }
        });
    }

    /**
     * @Deprecated 执行小程序接单
     */
    public static void submitWeChatMiniOrder(SuccessOrder successOrder) {
        OkHttpClient client = new OkHttpClient();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("systemPlatform", "ios");
        hashMap.put("mobileModel", "");
        hashMap.put("driverJourneyGuid", successOrder.getDriverJourneyGuid() == null ? Constant.routeId : successOrder.getDriverJourneyGuid());
        hashMap.put("mobileSystem", "iOS 16.6");
        hashMap.put("planArriveTime", "");
        hashMap.put("SDKVersion", Constant.SDK_VERSION);
        hashMap.put("lon", successOrder.getLon());
        hashMap.put("action", "hitch.driver.receiveOrder");

        HashMap<String, Object> riskControlData = new HashMap<>();
        riskControlData.put("batteryLevel", "42");
        riskControlData.put("openId", "");
        riskControlData.put("unionId", "");
        riskControlData.put("deviceLon", successOrder.getLon());
        riskControlData.put("deviceLat", successOrder.getLat());
        riskControlData.put("systemCode", "64");
        riskControlData.put("network", "wifi");
        hashMap.put("riskControlData", riskControlData);

        HashMap<String, Object> driverStartAddress = new HashMap<>();
        driverStartAddress.put("cityCode", successOrder.getCityCode());
        driverStartAddress.put("shortAddr", successOrder.getShortAddr());
        driverStartAddress.put("adCode", successOrder.getAdCode());
        driverStartAddress.put("poiId", "");
        driverStartAddress.put("lon", successOrder.getSjLon());
        driverStartAddress.put("lat", successOrder.getSjLat());
        driverStartAddress.put("longAddr", "");
        driverStartAddress.put("cityName", "");
        driverStartAddress.put("type", "");
        hashMap.put("driverStartAddress", driverStartAddress);

        hashMap.put("systemCode", 64);
        hashMap.put("version", Constant.HALLO_VERSION);
        hashMap.put("sourceType", "1");
        hashMap.put("paxJourneyGuid", successOrder.getPaxJourneyGuid());
        hashMap.put("ticket", Constant.ticket);
        hashMap.put("adCode", successOrder.getAdCode());
        hashMap.put("appName", "AppHitchDriverApplyWXMP");
        hashMap.put("token", Constant.token);
        hashMap.put("useDefaultVehicle", false);
        hashMap.put("hitchPercent", 0.99);
        hashMap.put("from", "weChat");
        hashMap.put("lat", successOrder.getLat());
        hashMap.put("cityCode", successOrder.getCityCode());
        hashMap.put("receiveSourceType", 7);
        hashMap.put("releaseVersion", Constant.RELEASE_VERSION);
        hashMap.put("weChatVersion", Constant.WECHAT_VERSION);
        MediaType mediaType = MediaType.parse("application/json");
        String jsonString = JSONObject.toJSONString(hashMap);
        RequestBody body = RequestBody.create(mediaType, jsonString);
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url("https://taxiapi.hellobike.com/api?hitch.driver.receiveOrder")
                .post(body)
                .addHeader("Host", "taxiapi.hellobike.com")
                .addHeader("Connection", "keep-alive")
                .addHeader("content-type", "application/json")
                .addHeader("Accept-Encoding", "gzip,compress,br,deflate")
                .addHeader("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.49(0x1800312d) NetType/WIFI Language/zh_CN")
                .build();
        // 发送请求并获取响应
        Response response = null;
        try {
            response = client.newCall(request).execute();
            assert response.body() != null;
            JSONObject jsonObject = JSONObject.parseObject(response.body().string());
            assert jsonObject != null;
            String status = jsonObject.getString("code");
            // 失败消息
            String msg = null;
            JSONObject data = jsonObject.getJSONObject("data");
            msg = jsonObject.getString("msg");
            if (status.equals("100000")) {
                JSONObject commonAlert = data.getJSONObject("commonAlert");
                // 拼接信息
                String title = commonAlert.getJSONObject("title").getString("text");
                String content = commonAlert.getJSONObject("content").getString("text");
                msg = title + ":" + content;
            }
            if (data != null) {
                if (status.equals("0") && data.getBoolean("joinPkSuccess")) {
                    msg = "成功加入PK.";
                } else {
                    JSONObject commonAlert = data.getJSONObject("commonAlert");
                    // 拼接信息
                    String title = commonAlert.getJSONObject("title").getString("text");
                    String content = commonAlert.getJSONObject("content").getString("text");
                    msg = title + ":" + content;
                }
            }
            if (status.equals("880")) {
                msg = "此订单已加入PK";
            }
            if (status.equals("865")) {
                msg = "成功加入PK";
            }
            if (status.equals("10000")) {
                msg = "小程序未刷脸认证";
                Constant.isStart = false;
            }
            if (status.equals("103")) {
                msg = "主号登录过期";
                Constant.isStart = false;
            }
            HomeFragment.updateStartCodeText(msg);
            successOrder.setOrderType("小程序");
            LogManager.get().addLog(msg);
            if (!Constant.mediaPlayer.isPlaying()) {
                Constant.mediaPlayer.start();
            }
            String finalMsg = msg;
            new Thread(() -> {
                MyProjectHttpUtil.addUserOrder(successOrder);
            }).start();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /***
     * @Deprecated 获取自己接的订单和自己发布的行程订单
     */
    public static JSONObject getWeChatMiniMyOrderOrMyScheduleOrder() {
        OkHttpClient client = new OkHttpClient();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("systemPlatform", "ios");
        hashMap.put("mobileModel", "");
        hashMap.put("mobileSystem", "iOS 16.6");
        hashMap.put("SDKVersion", "3.4.4");
        hashMap.put("action", "hitch.core.checkJourneyListV2");
        hashMap.put("lon", Constant.cityInfo.getLng());// 经度

        HashMap<String, Object> riskControlData = new HashMap<>();
        riskControlData.put("batteryLevel", "48");
        riskControlData.put("openId", "");
        riskControlData.put("unionId", "");
        riskControlData.put("deviceLon", Constant.cityInfo.getLng()); // 经度
        riskControlData.put("deviceLat", Constant.cityInfo.getLat()); // 纬度
        riskControlData.put("systemCode", "64");
        riskControlData.put("network", "wifi");
        hashMap.put("riskControlData", riskControlData);

        hashMap.put("systemCode", "64");
        hashMap.put("version", "6.68.0");
        hashMap.put("ticket", Constant.ticket);


        hashMap.put("journeyTypeList", "");

        hashMap.put("adCode", Constant.cityInfo.getAdCode());// 邮编
        hashMap.put("appName", "AppHitchDriverApplyWXMP");
        hashMap.put("token", Constant.token);
        hashMap.put("userNewId", null);
        hashMap.put("from", "weChat");
        hashMap.put("cityCode", Constant.cityInfo.getCityId()); // 区号
        hashMap.put("lat", Constant.cityInfo.getLat());// 纬度
        hashMap.put("releaseVersion", "6.63.0");
        hashMap.put("weChatVersion", "8.0.49");
        MediaType mediaType = MediaType.parse("application/json");
        String jsonString = JSONObject.toJSONString(hashMap);
        RequestBody body = RequestBody.create(mediaType, jsonString);
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url("https://taxiapi.hellobike.com/api?hitch.core.checkJourneyListV2")
                .post(body)
                .addHeader("Host", "taxiapi.hellobike.com")
                .addHeader("Connection", "keep-alive")
                .addHeader("content-type", "application/json")
                .addHeader("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.49(0x1800312d) NetType/WIFI Language/zh_CN")
                .build();
        // 发送请求并获取响应
        Response response = null;
        try {
            response = client.newCall(request).execute();

            assert response.body() != null;
            JSONObject jsonObject = JSONObject.parseObject(response.body().string());
            assert jsonObject != null;
            String status = jsonObject.getString("code");
            if (status.equals("0")) {
                return jsonObject;
            } else {
                return jsonObject;
            }
        } catch (IOException e) {
            return null;
        }
    }


    private static String configureTasks() {
        String url = "http://103.36.167.125:81/hallo-api/initTxm";
        String result = null;
        try {
            result = MyProjectHttpUtil.doGet1(url);
        } catch (IOException e) {
            return null;
        }
        return result;
    }

}
